package com.jinbiao.quasar.handler;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import cn.hutool.json.JSONUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.constant.RedisBucketKey;
import com.jinbiao.quasar.dto.LoginDto;
import com.jinbiao.quasar.model.SysLogLogin;
import com.jinbiao.quasar.model.SysLogOperation;
import com.jinbiao.quasar.model.SysUser;
import com.jinbiao.quasar.util.AjaxJson;
import com.jinbiao.quasar.util.RedisUtil;
import org.noear.redisx.RedisClient;
import org.noear.redisx.plus.RedisBucket;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;

import java.io.IOException;

public class OperationLogHandler implements Handler {
    @Db
    SqlToyLazyDao dao;

    @Override
    public void handle(Context ctx) throws Throwable {
        new Runnable() {
            @Override
            public void run() {
                String userId = StpUtil.getLoginIdAsString();
                RedisClient client = RedisUtil.getClient();
                RedisBucket bucket = client.getBucket();
                String userStr = bucket.get(RedisBucketKey.USER + userId);
                SysUser user = JSONUtil.toBean(userStr, SysUser.class);
                SysLogOperation logOperation = new SysLogOperation();
                logOperation.setOperationIp(ctx.ip());
                logOperation.setOperationApi(ctx.path());
                logOperation.setOperationUsername(user.getUsername());
                logOperation.setOperationMethod(ctx.controller().getClass().getName()+"::"+ctx.action().method().getName());
                logOperation.setStable("yesNo_no");
                logOperation.setSort(1);
                try {
                    if(StrUtil.isNotEmpty(ctx.body())) {
                        logOperation.setOperationBody(JSONUtil.toJsonPrettyStr(ctx.body()));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                AjaxJson result = (AjaxJson) ctx.result;
                if (result.getCode() == 200) {
                    logOperation.setOperationStatus(result.getCode());
                    logOperation.setMemo("处理成功;");
                } else {
                    logOperation.setOperationStatus(result.getCode());
                    logOperation.setMemo("处理失败;");
                }
                dao.save(logOperation);
            }
        }.run();
    }
}
